package com.linln.admin.welfare.controller;

import com.linln.admin.welfare.domain.Welfare;
import com.linln.admin.welfare.service.WelfareService;
import com.linln.admin.welfare.validator.WelfareValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.service.DeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

/**
 * @author wcy
 * @date 2020/03/14
 */
@Controller
@RequestMapping("/welfare/welfare")
public class WelfareController {

    @Autowired
    private WelfareService welfareService;
    @Autowired
    private DeptService deptService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("welfare:welfare:index")
    public String index(Model model, Welfare welfare) {

        //只能查找本用户的
        welfare.setUserId(ShiroUtil.getSubject().getId());

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("code", match -> match.contains());

        // 获取数据列表
        Example<Welfare> example = Example.of(welfare, matcher);
        Page<Welfare> list = welfareService.getPageList(example);

        list.getContent().forEach(line->{
            if (!StringUtils.isEmpty(line.getStartDate())){
                line.setStartDate(line.getStartDate().replace("T"," "));
                line.setEndDate(line.getEndDate().replace("T"," "));
            }
        });
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/welfare/welfare/index";
    }

    @GetMapping("/cancel")
    @RequiresPermissions("welfare:welfare:cancel")
    public String cancel(Model model, Welfare welfare) {

        //只能查找本用户的
        welfare.setUserId(ShiroUtil.getSubject().getId());
//        welfare.setMove(0L);
//        welfare.setStatus((byte) 1);
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("code", match -> match.contains());

        // 获取数据列表
        Example<Welfare> example = Example.of(welfare, matcher);

        Page<Welfare> list = welfareService.getPageList(example);
        list.getContent().forEach(line->{
            if (!StringUtils.isEmpty(line.getStartDate())){
                line.setStartDate(line.getStartDate().replace("T"," "));
                line.setEndDate(line.getEndDate().replace("T"," "));
            }
        });
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/welfare/welfare/cancel";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("welfare:welfare:add")
    public String toAdd() {
        return "/welfare/welfare/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("welfare:welfare:edit")
    public String toEdit(@PathVariable("id") Welfare welfare, Model model) {
        model.addAttribute("welfare", welfare);
        return "/welfare/welfare/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"welfare:welfare:add", "welfare:welfare:edit"})
    @ResponseBody
    public ResultVo save(@Validated WelfareValid valid, Welfare welfare) {
        // 复制保留无需修改的数据
        if (welfare.getId() != null) {
            Welfare beWelfare = welfareService.getById(welfare.getId());
            EntityBeanUtil.copyProperties(beWelfare, welfare);
        }
//        welfare.setCode(welfare.getCode()+welfare.getType()+System.currentTimeMillis());
        welfare.setCode(String.valueOf(System.currentTimeMillis()));
        welfare.setUserId(ShiroUtil.getSubject().getId());
        //将流转ID换为上级部门
        welfare.setMove(0L);
//        welfare.setMove(ShiroUtil.getSubject().getDept().getPid());
        //设置状态为2，正在审核
        welfare.setStatus((byte) 2);
        // 保存数据
        welfareService.save(welfare);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("welfare:welfare:detail")
    public String toDetail(@PathVariable("id") Welfare welfare, Model model) {
        model.addAttribute("welfare",welfare);
        return "/welfare/welfare/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("welfare:welfare:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if ("cancel".equals(param)){
            Welfare beWelfare = welfareService.getById(ids.get(0));
            beWelfare.setMove(1L);
            beWelfare.setStatus((byte) 4);
            welfareService.save(beWelfare);
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        }else {
            if (welfareService.updateStatus(statusEnum, ids)) {
                return ResultVoUtil.success(statusEnum.getMessage() + "成功");
            } else {
                return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
            }
        }
    }
}